package com.jtlrm.ckd.mvp.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.CommonUtil;
import com.base.sdk.util.DateFormatUtil;
import com.base.sdk.util.GetJsonDataUtil;
import com.base.sdk.util.ValidateUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.AreaEntity;
import com.jtlrm.ckd.entity.ByPhoneHuanZheInfo;
import com.jtlrm.ckd.entity.CodeEntity;
import com.jtlrm.ckd.entity.event.SelectBanSuiMessage;
import com.jtlrm.ckd.entity.submitEntity.HuanZheJianDangData;
import com.jtlrm.ckd.mvp.model.HuanZheGuanLiModel;
import com.jtlrm.ckd.mvp.model.ResourceModel;
import com.jtlrm.ckd.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class NewHuanZheJianDangActivity2 extends TitleBarActivity implements View.OnClickListener {

    private static final int MSG_LOAD_FAILED = 0x0003;
    private ArrayList<AreaEntity> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    String phone;
    @BindView(R.id.man)
    RadioButton manC;
    @BindView(R.id.woman)
    RadioButton womanC;
    @BindView(R.id.hint)
    TextView hintT;
    @BindView(R.id.name)
    EditText nameE;
    @BindView(R.id.sex)
    RadioGroup sexR;
    @BindView(R.id.birthday)
    TextView birthdayT;
    @BindView(R.id.address)
    TextView addressT;
    @BindView(R.id.detail_address)
    EditText detailAddressE;
    @BindView(R.id.id_card)
    EditText idCardE;
    @BindView(R.id.education)
    TextView educationT;
    @BindView(R.id.bao_xiao_style)
    TextView baoXiaoStyleT;
    @BindView(R.id.yuanfabing)
    TextView yuanFaBingT;
    @BindView(R.id.bansuibing)
    TextView banSuiBingT;
    @BindView(R.id.remark)
    EditText remarkE;
    @BindView(R.id.jiandang)
    Button jianDangB;
    @BindView(R.id.jiandang_zhenliao)
    Button jianDangZhenLiaoB;
    TimePickerView birthDay;
    private boolean isLoaded = false;
    HuanZheJianDangData submitData = new HuanZheJianDangData();
    ResourceModel resourceModel;
    List<CodeEntity> wenHuanChengDu = new ArrayList<>();
    List<CodeEntity> baoXiaoFangShi = new ArrayList<>();
    List<CodeEntity> yuanFaBing = new ArrayList<>();
    List<CodeEntity> banSuiJiBing = new ArrayList<>();
    HuanZheGuanLiModel huanZheGuanLiModel;
    ByPhoneHuanZheInfo initInfo;

    public static void goActivity(Context context, String phone, ByPhoneHuanZheInfo info) {
        Intent intent = new Intent(context, NewHuanZheJianDangActivity2.class);
        intent.putExtra("phone", phone);
        intent.putExtra("entity", info);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        phone = getIntent().getStringExtra("phone");
        initInfo = (ByPhoneHuanZheInfo) getIntent().getSerializableExtra("entity");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        return "新患者建档";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_new_huan_zhe_jian_dang2);
    }

    @Override
    protected void initView() {
        SpannableString spannableString = new SpannableString("完善手机号码" + phone + "用户的建档信息");
        //设置颜色
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#F7A98B")), 6, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        hintT.setText(spannableString);
        submitData.setLoginPhone(phone);
        submitData.setSex(0);
        birthDay = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                birthdayT.setText(DateFormatUtil.dateFormatAll(date.getTime()));
                submitData.setBrithday(DateFormatUtil.dateFormatLine(date.getTime()));
            }
        }).build();
        resourceModel = new ResourceModel();
        huanZheGuanLiModel = new HuanZheGuanLiModel();
        initCode(ResourceModel.KeyCode.WEN_HUAN_CHENGDU, wenHuanChengDu);
        initCode(ResourceModel.KeyCode.BAO_XIAO_FANG_SHI, baoXiaoFangShi);
        initCode(ResourceModel.KeyCode.YUAN_FA_BING, yuanFaBing);
        initCode(ResourceModel.KeyCode.BAN_SUI_JI_BING, banSuiJiBing);
        EventBusUtil.register(this);
    }


    @Override
    protected void obtainData() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 子线程中解析省市区数据解析完了再请求个人数据
                initJsonData();
            }
        });
        thread.start();
        if (initInfo != null) {
            try {
//                if ("app".equals((initInfo.getRegisterType() + "").toLowerCase())) {
//                    setStatus(false);
//                } else {
//                    setStatus(true);
//                }
                setStatus(false);
                update();
            } catch (Exception e) {
                e.toString();
            }
        }
    }

    private void setStatus(boolean isEdit) {
        nameE.setEnabled(isEdit);
//        sexR.setEnabled(isEdit);
//        manC.setEnabled(isEdit);
//        womanC.setEnabled(isEdit);
//        birthdayT.setEnabled(isEdit);
       // addressT.setEnabled(isEdit);
       // detailAddressE.setEnabled(isEdit);
        //idCardE.setEnabled(isEdit);
        //educationT.setEnabled(isEdit);
       // baoXiaoStyleT.setEnabled(isEdit);
       // yuanFaBingT.setEnabled(isEdit);
       // banSuiBingT.setEnabled(isEdit);
       // remarkE.setEnabled(isEdit);
//        if (isEdit) {
//            jianDangB.setVisibility(View.VISIBLE);
//            jianDangZhenLiaoB.setVisibility(View.VISIBLE);
//        } else {
//            jianDangB.setVisibility(View.GONE);
//            jianDangZhenLiaoB.setVisibility(View.GONE);
//        }
    }

    /**
     * 初始化数据
     */
    private void update() {
        setText(nameE, initInfo.getName());
        if ("0".equals(initInfo.getSex() + "")) {
            manC.setChecked(true);
        } else {
            womanC.setChecked(true);
        }
        setText(birthdayT, initInfo.getBrithday());
        setText(detailAddressE, initInfo.getFullAddress());
        setText(idCardE, initInfo.getCardNo());
        setText(remarkE, initInfo.getRemarkCKD());
        submitData.setName(initInfo.getName());
        submitData.setSex(Integer.parseInt(initInfo.getSex()));
        submitData.setBrithday(initInfo.getBrithday());
        if (initInfo.getAreaCode() != null)
            submitData.setAreaCode(Long.parseLong(initInfo.getAreaCode()));
        submitData.setFullAddress(initInfo.getFullAddress());
        submitData.setCardNo(initInfo.getCardNo());
        if (initInfo.getEducation() != null)
            submitData.setEducation(Integer.parseInt(initInfo.getEducation()));
        if (initInfo.getExpenseType() != null)
            submitData.setExpenseType(Integer.parseInt(initInfo.getExpenseType()));
        submitData.setOrgDisease(initInfo.getOrgDisease());
        submitData.setWithDisease(initInfo.getWithDisease());
        submitData.setRemarkCKD(initInfo.getRemarkCKD());
    }

    private void initJsonData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "area.js");//获取assets目录下的json文件数据
        options1Items = parseData(JsonData);
        for (int i = 0; i < options1Items.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < options1Items.get(i).getChildren().size(); c++) {//遍历该省份的所有城市
                String CityName = options1Items.get(i).getChildren().get(c).getAreaName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (options1Items.get(i).getChildren().get(c).getChildren() == null
                        || options1Items.get(i).getChildren().get(c).getChildren().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (AreaEntity entity : options1Items.get(i).getChildren().get(c).getChildren())
                        City_AreaList.add(entity.getAreaName());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
            isLoaded = true;
            // 更新地区数据
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (initInfo != null) {
                        String area = "";
                        loop1:
                        for (AreaEntity entity : options1Items) {
                            if ((entity.getId() + "").equals(initInfo.getProvinceCode())) {
                                area = entity.getAreaName();
                                loop2:
                                for (AreaEntity citys : entity.getChildren()) {
                                    if ((citys.getId() + "").equals(initInfo.getCityCode())) {
                                        area = area + "/" + citys.getAreaName();
                                        loop3:
                                        for (AreaEntity areaEntity : citys.getChildren()) {
                                            if ((areaEntity.getId() + "").equals(initInfo.getAreaCode())) {
                                                area = area + "/" + areaEntity.getAreaName();
                                                break loop1;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        setText(addressT, area);
                    }
                }
            });
        }
    }

    @Override
    protected void initEvent() {
        sexR.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.man) {
                    submitData.setSex(0);
                } else if (checkedId == R.id.woman) {
                    submitData.setSex(1);
                }
            }
        });
        birthdayT.setOnClickListener(this);
        addressT.setOnClickListener(this);
        educationT.setOnClickListener(this);
        baoXiaoStyleT.setOnClickListener(this);
        yuanFaBingT.setOnClickListener(this);
        banSuiBingT.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.birthday:
                CommonUtil.hideSoftInput(context, sexR);
                birthDay.show();
                break;
            case R.id.address:
                CommonUtil.hideSoftInput(context, sexR);
                showAdressSelect();
                break;
            case R.id.education:
                CommonUtil.hideSoftInput(context, sexR);
                showSelect(wenHuanChengDu, educationT, ResourceModel.KeyCode.WEN_HUAN_CHENGDU, "请选择教育程度");
                break;
            case R.id.bao_xiao_style:
                CommonUtil.hideSoftInput(context, sexR);
                showSelect(baoXiaoFangShi, baoXiaoStyleT, ResourceModel.KeyCode.BAO_XIAO_FANG_SHI, "请选择报销方式");
                break;
            case R.id.yuanfabing:
                CommonUtil.hideSoftInput(context, sexR);
                showSelect(yuanFaBing, yuanFaBingT, ResourceModel.KeyCode.YUAN_FA_BING, "请选择原发病");
                break;
            case R.id.bansuibing:
                CommonUtil.hideSoftInput(context, sexR);
                startActivity(new Intent(context, BanSuiJiBingActivity.class));
                break;
        }
    }

    private void showSelect(final List<CodeEntity> list, final TextView text, final String key, String title) {
        if (list == null || list.size() == 0) {
            showToast("暂无数据");
            return;
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                try {
                    CodeEntity codeEntity = list.get(options1);
                    setText(text, codeEntity.getName());
                    switch (key) {
                        case ResourceModel.KeyCode.WEN_HUAN_CHENGDU:
                            submitData.setEducation(Integer.parseInt(codeEntity.getId()));
                            break;
                        case ResourceModel.KeyCode.BAO_XIAO_FANG_SHI:
                            submitData.setExpenseType(Integer.parseInt(codeEntity.getId()));
                            break;
                        case ResourceModel.KeyCode.YUAN_FA_BING:
                            submitData.setOrgDisease(codeEntity.getId());
                            break;
                    }
                } catch (Exception e) {

                }
            }
        })

                .setTitleText(title)
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);//三级选择器
        pvOptions.show();
    }


    public void submit(View view) {
        upload(view);
    }


    public void submitAndZhiLiao(View view) {
        upload(view);
    }

    private void upload(final View view) {
        if (!validate()) {
            return;
        }
        showLoadingDialog("建档中");
        huanZheGuanLiModel.createHuanZheDangAn(submitData, new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(String data) {
                showToast("建档成功");
                dismissLoadingDialog();
                if (view.getId() == R.id.jiandang_zhenliao) {
                    HuanZheManagerActivity.goActivity(context, data);
                }
                finish();
            }
        }, lifecycleSubject);
    }

    public boolean validate() {
        submitData.setName(getTextStr(nameE));
        if (!notEmpty(submitData.getName())) {
            showToast("请输入姓名");
            return false;
        }
        if (submitData.getBrithday() == null) {
            showToast("请选择出生日期");
            return false;
        }
        String idCard = getTextStr(idCardE);
        if (notEmpty(idCard) && !ValidateUtils.IDcard(idCard)) {
            showToast("请输入正确的身份证号码");
            return false;
        }
        submitData.setCardNo(idCard);
        submitData.setFullAddress(getTextStr(detailAddressE));
        submitData.setRemarkCKD(getTextStr(remarkE));
        return true;
    }

    private void showAdressSelect() {
        if (!isLoaded) {
            showToast("位置数据还未加载完请稍后");
            return;
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                try {
                    String tx = options1Items.get(options1).getPickerViewText() + "/" +
                            options2Items.get(options1).get(options2) + "/" +
                            options3Items.get(options1).get(options2).get(options3);
                    addressT.setText(tx);
                    submitData.setAreaCode(options1Items.get(options1).getChildren().get(options2).getChildren().get(options3).getId());

                } catch (Exception e) {

                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_FAILED:
                    showToast("位置数据解析失败");
                    break;
            }
        }
    };

    public ArrayList<AreaEntity> parseData(String result) {//Gson 解析
        ArrayList<AreaEntity> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AreaEntity entity = gson.fromJson(data.optJSONObject(i).toString(), AreaEntity.class);
                detail.add(entity);
            }

        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void initCode(final String key, final List<CodeEntity> list) {
        resourceModel.getCode(key, new CommonObserver<List<CodeEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(List<CodeEntity> data) {
                if (data == null || data.size() == 0) {
                    return;
                }
                try {
                    list.addAll(data);
                    updateSelect(key, data);
                } catch (Exception e) {
                }
            }
        }, lifecycleSubject);
    }

    private void updateSelect(String key, List<CodeEntity> data) {
        if (initInfo != null) {
            switch (key) {
                case ResourceModel.KeyCode.WEN_HUAN_CHENGDU:
                    for (CodeEntity entity : data) {
                        if (initInfo.getEducation().equals(entity.getId())) {
                            setText(educationT, entity.getName());

                            break;
                        }
                    }
                    break;
                case ResourceModel.KeyCode.YUAN_FA_BING:
                    String[] idss = initInfo.getOrgDisease().split(",");
                    String ori = "";
                    for (String id : idss) {
                        for (CodeEntity entity : data) {
                            if (id.equals(entity.getId())) {
                                if (notEmpty(ori)) {
                                    ori = ori + "," + entity.getName();
                                } else {
                                    ori = entity.getName();
                                }
                                continue;
                            }
                        }
                    }
                    setText(yuanFaBingT, ori);
                    break;
                case ResourceModel.KeyCode.BAN_SUI_JI_BING:
                    String[] ids = initInfo.getWithDisease().split(",");
                    String banSui = "";
                    for (String id : ids) {
                        for (CodeEntity entity : data) {
                            if (id.equals(entity.getId())) {
                                if (notEmpty(banSui)) {
                                    banSui = banSui + "," + entity.getName();
                                } else {
                                    banSui = entity.getName();
                                }
                                continue;
                            }
                        }
                    }
                    setText(banSuiBingT, banSui);
                    break;
                case ResourceModel.KeyCode.BAO_XIAO_FANG_SHI:
                    for (CodeEntity entity : data) {
                        if (initInfo.getExpenseType().equals(entity.getId())) {
                            setText(baoXiaoStyleT, entity.getName());
                            break;
                        }
                    }
                    break;
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SelectBanSuiMessage event) {
        if (event != null && event.getData().size() > 0) {
            String bansui = "";
            String code = "";
            for (CodeEntity entity : event.getData()) {
                if (notEmpty(bansui)) {
                    bansui = bansui + "," + entity.getName();
                    code = code + "," + entity.getId();
                } else {
                    bansui = entity.getName();
                    code = entity.getId();
                }
            }
            submitData.setWithDisease(code);
            setText(banSuiBingT, bansui);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }

}
